package de.zinulla.moviethek;

import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.os.Bundle;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;

import de.zinulla.common.MoviethekConstants;
import de.zinulla.moviethek.contentprovider.MoviethekContentProvider;
import de.zinulla.moviethek.fragments.DetailFragment;

public class MovieDetailActivity extends SherlockFragmentActivity {

	long searchId;
	private DetailFragment details;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Need to check if Activity has been switched to landscape mode
		// If yes, finished and go back to the start Activity
//		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
//
//			return;
//		}
		if (getResources().getConfiguration().isLayoutSizeAtLeast(Configuration.SCREENLAYOUT_SIZE_XLARGE)) {
			
			return;
		}
		SharedPreferences settings = getSharedPreferences(MoviethekConstants.MOVIE_SP, 0);
		searchId = settings.getLong(MoviethekConstants.MOVIE_ID, 0);
		// Show the new fragment (full screen)
//		DetailFragment details = DetailFragment.newInstance(searchId);
//		DetailFragment details = new DetailFragment();
//		getSupportFragmentManager().beginTransaction().add(android.R.id.content, details).commit();

		details = (DetailFragment) getSupportFragmentManager().findFragmentById(android.R.id.content);
		if(details == null){
			details = new DetailFragment();
			getSupportFragmentManager().beginTransaction().add(android.R.id.content, details).commit();
		} else {
			return;
		}
		
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		MenuInflater inflater = (MenuInflater) getSupportMenuInflater();
//		inflater.inflate(R.menu.list_menu, menu);
        //Used to put dark icons on light action bar
	   menu.add("Delete")
           .setIcon(android.R.drawable.ic_menu_delete)
           .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);

		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		SharedPreferences settings = this.getSharedPreferences(MoviethekConstants.MOVIE_SP, 0);
		long id = settings.getLong(MoviethekConstants.MOVIE_ID, 0);
		// Handle item selection
		if("Delete".equals(item.getTitle())){
			deleteMovie(id);
		} else {
			return super.onOptionsItemSelected(item);
		}

		return true;
	}
	
	private void deleteMovie(long id){
		int c = this.getContentResolver().delete(MoviethekContentProvider.createDeleteUri(id), null, null);
		finish();
	}


}
